<script setup>
import ip from '@/utils/baseURL.js';
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import axios from 'axios';
import debounce from 'lodash/debounce';

// 获取当前用户的 session
const session = localStorage.getItem('session');

// API基础URL
const apiBaseUrl = ip + '/inter';

// 表格数据和加载状态
const projectList = ref([]);
const tableLoading = ref(false);

// 搜索关键词
const searchKeyword = ref('');

// 年份和状态筛选
const selectedYear = ref('');
const selectedStatus = ref('');
const availableYears = ref([]);
const allProjects = ref([]); // 存储所有项目数据，用于前端筛选

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框控制
const dialogVisible = ref(false);
const isEditing = ref(false);
const submitting = ref(false);

// 表单引用和数据
const projectFormRef = ref(null);
const projectForm = reactive({
  projectId: null,
  projectName: '',
  mainPeople: '',
  member: '',
  status: 0,
  startTimeString: '', // 用于日期选择器
  endTimeString: '', // 用于日期选择器
  briInfo: '',
  fruits: ''
});

// 表单验证规则
const formRules = {
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  mainPeople: [
    { required: true, message: '请输入项目负责人', trigger: 'blur' }
  ],
  member: [
    { required: true, message: '请输入项目成员', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择项目状态', trigger: 'change' }
  ],
  startTimeString: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTimeString: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statusMap = {
    0: 'info', // 未开始
    1: 'warning', // 进行中
    2: 'success' // 已完成
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusLabel = (status) => {
  const statusMap = {
    0: '未开始',
    1: '进行中',
    2: '已完成'
  };
  return statusMap[status] || '未知状态';
};

// 格式化日期数组为显示字符串
const formatDateDisplay = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray) || dateArray.length < 3) {
    return '未设置';
  }
  const [year, month, day] = dateArray;
  // 补充前导零
  const formattedMonth = month.toString().padStart(2, '0');
  const formattedDay = day.toString().padStart(2, '0');
  return `${year}-${formattedMonth}-${formattedDay}`;
};

// 处理年份变化
const handleYearChange = () => {
  filterProjects();
};

// 处理状态变化
const handleStatusChange = () => {
  filterProjects();
};

// 根据筛选条件过滤项目
const filterProjects = () => {
  let filtered = [...allProjects.value];
  
  // 应用年份筛选
  if (selectedYear.value) {
    filtered = filtered.filter(project => {
      if (project.startTime && Array.isArray(project.startTime) && project.startTime.length > 0) {
        return project.startTime[0] === selectedYear.value;
      }
      return false;
    });
  }
  
  // 应用状态筛选
  if (selectedStatus.value !== '') {
    filtered = filtered.filter(project => project.status === selectedStatus.value);
  }
  
  projectList.value = filtered;
  pagination.total = filtered.length;
};

// 加载项目列表数据
const loadProjectList = async () => {
  tableLoading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value || undefined
    };
    
    const response = await axios.get(`${apiBaseUrl}/project/getOurProjects`, { params });
    
    if (response.data.code === 200) {
      const records = response.data.data.records || [];
      allProjects.value = records;
      
      // 提取所有可用的年份
      const years = new Set();
      records.forEach(project => {
        if (project.startTime && Array.isArray(project.startTime) && project.startTime.length > 0) {
          years.add(project.startTime[0]);
        }
      });
      availableYears.value = Array.from(years).sort((a, b) => b - a); // 降序排列
      
      // 应用筛选
      filterProjects();
      
      pagination.total = response.data.data.count || 0;
    } else {
      ElMessage.error(response.data.message || '获取项目信息失败');
    }
  } catch (error) {
    console.error('加载项目信息错误:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

// 搜索防抖
const debounceSearch = debounce(() => {
  pagination.currentPage = 1;
  loadProjectList();
}, 300);

// 处理页面大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadProjectList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadProjectList();
};

// 添加项目信息
const handleAddProject = () => {
  isEditing.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 编辑项目信息
const handleEditProject = (row) => {
  isEditing.value = true;
  resetForm();
  
  // 复制数据到表单
  projectForm.projectId = row.projectId;
  projectForm.projectName = row.projectName;
  projectForm.mainPeople = row.mainPeople;
  projectForm.member = row.member;
  projectForm.status = row.status;
  projectForm.startTimeString = formatDateDisplay(row.startTime);
  projectForm.endTimeString = formatDateDisplay(row.endTime);
  projectForm.briInfo = row.briInfo;
  projectForm.fruits = row.fruits;
  
  dialogVisible.value = true;
};

// 删除项目信息
const handleDeleteProject = (row) => {
  ElMessageBox.confirm(`确定要删除项目"${row.projectName}"吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用正确的删除API
      const response = await axios.delete(`${apiBaseUrl}/adminProject/delete?projectId=${row.projectId}`,{headers: {
        'Session': `${session}`, // 传递 session
      },
      });
      
      if (response.data.code === 200) {
        ElMessage.success('删除成功');
        loadProjectList();
      } else {
        ElMessage.error(response.data.message || '删除失败');
      }
    } catch (error) {
      console.error('删除项目信息错误:', error);
      ElMessage.error('网络错误，请稍后重试');
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  if (projectFormRef.value) {
    projectFormRef.value.resetFields();
  }
  projectForm.projectId = null;
  projectForm.projectName = '';
  projectForm.mainPeople = '';
  projectForm.member = '';
  projectForm.status = 0;
  projectForm.startTimeString = '';
  projectForm.endTimeString = '';
  projectForm.briInfo = '';
  projectForm.fruits = '';
};

// 提交项目表单
const submitProjectForm = () => {
  projectFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // 转换成后端期望的格式
        const formData = {
          // 有id就是修改，没有就是新增
          ...(projectForm.projectId ? { projectId: projectForm.projectId } : {}),
          projectName: projectForm.projectName,
          mainPeople: projectForm.mainPeople,
          member: projectForm.member,
          status: projectForm.status,
          startTime: projectForm.startTimeString, // 直接使用日期字符串
          endTime: projectForm.endTimeString,     // 直接使用日期字符串
          briInfo: projectForm.briInfo,
          fruits: projectForm.fruits
        };
        
        // 使用正确的接口URL
        const url = `${apiBaseUrl}/adminProject/saveOrUpdate`;
          
        const response = await axios.post(url, formData,{headers: {
          'Session': `${session}`, // 传递 session
        },
        });
        
        if (response.data.code === 200) {
          ElMessage.success(isEditing.value ? '更新成功' : '添加成功');
          dialogVisible.value = false;
          loadProjectList();
        } else {
          ElMessage.error(response.data.message || (isEditing.value ? '更新失败' : '添加失败'));
        }
      } catch (error) {
        console.error('提交项目信息错误:', error);
        ElMessage.error('网络错误，请稍后重试');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 页面初始化时加载数据
onMounted(() => {
  loadProjectList();
});
</script>

<template>
  <div class="project-container">
    <div class="page-header">
      <h1>项目信息管理</h1>
    </div>

    <!-- 功能按钮区域 -->
    <div class="actions-panel">
      <el-button type="primary" @click="handleAddProject">添加项目</el-button>
      <div class="filter-panel">
        <el-select
          v-model="selectedYear"
          placeholder="选择年份"
          clearable
          @change="handleYearChange"
          class="year-select"
        >
          <el-option
            v-for="year in availableYears"
            :key="year"
            :label="year + '年'"
            :value="year"
          />
        </el-select>
        <el-select
          v-model="selectedStatus"
          placeholder="项目状态"
          clearable
          @change="handleStatusChange"
          class="status-select"
        >
          <el-option label="进行中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="未开始" :value="0" />
        </el-select>
        <div class="search-panel">
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索项目名称或负责人" 
            clearable 
            @clear="loadProjectList" 
            @input="debounceSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </div>

    <!-- 项目信息表格 -->
    <el-table 
      :data="projectList" 
      style="width: 100%" 
      border 
      v-loading="tableLoading"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="projectName" label="项目名称" min-width="180" />
      <el-table-column prop="mainPeople" label="负责人" width="100" />
      <el-table-column prop="member" label="项目成员" min-width="150" />
      <el-table-column label="项目状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="起止时间" width="200">
        <template #default="scope">
          {{ formatDateDisplay(scope.row.startTime) }} 至 {{ formatDateDisplay(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="briInfo" label="项目简介" min-width="200">
        <template #default="scope">
          <div class="brief-cell">
            {{ scope.row.briInfo || '暂无简介' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="fruits" label="项目成果" min-width="200">
        <template #default="scope">
          <div class="brief-cell">
            {{ scope.row.fruits || '暂无成果' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditProject(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteProject(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑项目信息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑项目信息' : '添加项目'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="projectForm" label-width="100px" :rules="formRules" ref="projectFormRef">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="projectForm.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目负责人" prop="mainPeople">
          <el-input v-model="projectForm.mainPeople" placeholder="请输入项目负责人" />
        </el-form-item>
        <el-form-item label="项目成员" prop="member">
          <el-input v-model="projectForm.member" placeholder="请输入项目成员，多个成员用逗号分隔" />
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="projectForm.status" placeholder="请选择项目状态" style="width: 100%">
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTimeString">
          <el-date-picker 
            v-model="projectForm.startTimeString" 
            type="date" 
            placeholder="选择开始时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTimeString">
          <el-date-picker 
            v-model="projectForm.endTimeString" 
            type="date" 
            placeholder="选择结束时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="项目简介" prop="briInfo">
          <el-input 
            v-model="projectForm.briInfo"
            type="textarea"
            :rows="3"
            placeholder="请输入项目简介"
          />
        </el-form-item>
        <el-form-item label="项目成果" prop="fruits">
          <el-input 
            v-model="projectForm.fruits"
            type="textarea"
            :rows="3"
            placeholder="请输入项目成果"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProjectForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>



<style lang="scss" scoped>
.project-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .actions-panel {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    
    .filter-panel {
      display: flex;
      gap: 10px;
      align-items: center;
      
      .year-select, .status-select {
        width: 120px;
      }
      
      .search-panel {
        width: 250px;
      }
    }
  }
  
  .brief-cell {
    max-width: 250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.el-table) {
  margin-bottom: 20px;
}
</style>